package com.czh.subject.domain.utils;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.google.common.cache.Cache;
import com.google.common.cache.CacheBuilder;
import io.micrometer.common.util.StringUtils;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

/**
 * 本地缓存工具类
 *
 * @author caozaihui
 * @version 1.0
 * @since 2024/9/9 13:44
 */
@Component
public class CacheUtil<V> {
    /**
     * 缓存对象
     */
    private final Cache<String, String> cache =
            CacheBuilder.newBuilder().
                    maximumSize(5000).
                    expireAfterAccess(30, TimeUnit.MINUTES).
                    build();


    public List<V> getCacheList(String key, Class<V> clazz, Function<String, List<V>> function) {
        String objectValue = cache.getIfPresent(key);
        if (StringUtils.isBlank(objectValue)){
            objectValue = JSON.toJSONString(function.apply(key));
            cache.put(key,(objectValue));
        }
        return JSONArray.parseArray(objectValue, clazz);
    }

//    public Map<K, V> getCacheMap(String key, Class<K> keyClazz, Class<V> valueClazz, Function<String, Map<K, V>> function) {
//        String objectValue = cache.getIfPresent(key);
//        Map<K, V> resultMap;
//        if (StringUtils.isBlank(objectValue)) {
//            resultMap = function.apply(key);
//            cache.put(key, JSON.toJSONString(resultMap));
//        } else {
//            resultMap = JSON.parseObject(objectValue, new TypeReference<>(keyClazz, valueClazz) {});
//        }
//        return resultMap;
//    }
}
